package com.beiyou.orderingsystemonweb.system.other;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * 用户访问controller中拦截器部署的资源的时候会拦截
 */

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().endsWith(".data")){
            System.out.println("拦截器不拦截地址栏不是.data结尾，但是发送的ajax请求");
            return true;
        }
        else{
            String pattern = request.getContextPath()+"(/WEB-INF/|/)user.*";
            if (request.getSession().getAttribute("userId")!=null&&request.getRequestURI().matches(pattern)){
                return true;
            }
            else {
                //拼接pattern
                pattern = request.getContextPath()+"(/WEB-INF/|/)shop.*";
                if (request.getSession().getAttribute("shopId")!=null&&request.getRequestURI().matches(pattern)){
                    return true;
                }
                System.out.println("请求地址栏:"+request.getRequestURI());
                System.out.println("根地址栏:"+request.getContextPath()+"/shop");
                System.out.println("拦截器");
                response.sendRedirect(request.getContextPath()+"/");
                return false;
            }
        }
    }
}
